package com.haieros.www.purerunshowsystem;
import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.content.*;
import android.content.pm.IPackageInstallObserver;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.*;
import android.provider.Settings;
import android.support.v4.graphics.drawable.RoundedBitmapDrawable;
import android.support.v4.graphics.drawable.RoundedBitmapDrawableFactory;
import android.util.Log;
import android.view.*;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.BitmapImageViewTarget;
import com.google.gson.Gson;
import com.haieros.www.purerunshowsystem.activity.LaunchEquipmenActivity;
import com.haieros.www.purerunshowsystem.activity.MusicActivity;
import com.haieros.www.purerunshowsystem.bean.UpdateBean;
import com.haieros.www.purerunshowsystem.broadcast.DataChangeReceiver;
import com.haieros.www.purerunshowsystem.service.MQService;
import com.haieros.www.purerunshowsystem.service.MusicService;
import com.haieros.www.purerunshowsystem.socket.OnDataReceiveListener;
import com.haieros.www.purerunshowsystem.socket.SocketUtils;
import com.haieros.www.purerunshowsystem.tinker.Utils;
import com.haieros.www.purerunshowsystem.update.DeleteDialog;
import com.haieros.www.purerunshowsystem.update.PhoneDialog;
import com.haieros.www.purerunshowsystem.utils.*;
import com.othershe.dutil.callback.DownloadCallback;
import com.tencent.tinker.lib.tinker.TinkerInstaller;
import com.tencent.tinker.loader.shareutil.ShareTinkerInternals;
import com.youth.banner.Banner;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.FileCallBack;
import okhttp3.Call;
import okhttp3.Request;
import okhttp3.Response;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.io.*;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.ScheduledExecutorService;

//主类的开始
public class MainActivity extends BaseAcivity implements View.OnClickListener, OnDataReceiveListener {
    //轮播图banner
    Banner banner;
    private boolean mThirdAppTypeFlag;
    WindowManager.LayoutParams mParams;
    LayoutInflater mInflater;
    /**
     * 显示用户信息
     */
    private TextView mUserName;
    private ImageView ivHead;
    /**
     * 显示速度
     */
    private TextView mSpeed_tv;
    /**
     * 显示坡度
     */
    private TextView mGradient_tv;
    /**
     * 显示心率
     */
    private TextView mHeartrate_tv;
    /**
     * 显示路程
     */
    private TextView mSpeedunit_tv;
    /**
     * 显示时间
     */
    private TextView mTime_tv;
    /**
     * 显示能量消耗
     */
    private TextView mKcal_tv;
    // 视频地址集合
    private List<String> mlistStr = new ArrayList<>();
    // banner 轮播集合 存放视频搭载view  或图片搭载view
    private List<View> viewList = new ArrayList<>();
    // 视频地址集合
    private List<String> mlistVideoUri = new ArrayList<>();
    // 视频循环播放标记
    private int itemPosition = 0;
    // ViewPager Views
    private List<VideoViewUtil> mListVideo = new ArrayList<>();
    private Runnable runable;
    String timeNow;
    //设置时间得格式
    SimpleDateFormat formater = new SimpleDateFormat("HH:mm:ss");
    //获取当前时间
    Date date = new Date(System.currentTimeMillis());
    String a = "";
    //测试无用
    WindowManager mWindowManager;
    //=============ActiveMQ相关start==============
    private String host = "tcp://120.55.88.22:1883";
    private String userName = "admin";
    private String passWord = "admin";
    private int i = 1;
    private Handler mqHandler;
    private MqttClient client;
    private String myTopic = "AACAA2017081400200003";
    private MqttConnectOptions options;
    private ScheduledExecutorService scheduler;
    private String[] s;
    private String mqMessage = "";
    private SimpleDateFormat formate;
    private MyReceiver receiver = null;
    private Context mContext;
    private SDUtils sdUtils;
    private VideoViewUtil videoUtils;
    DataChangeReceiver receiverChange;
    //MainUpView mMainUpView;
    ImageView ivMusic, ivSetting, ivGuide, ivMultimedia;
    // EffectNoDrawBridge bridget;
    private View mActivityTopView;
    //=============ActiveMQ相关end==============
    //=============自动升级相关start==============
    private String filePath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/haier";
    private static String musicFilePath = "/data/music";
    private DeleteDialog deleteDialog;
    /* 通知用户更新 */
    private static final int UPDATA_CLIENT = 1;
    /* 服务器连接超时 */
    private static final int GET_UNDATAINFO_ERROR = 2;
    /* 下载失败 */
    private static final int DOWN_ERROR = 3;
    //=============自动升级相关end==============
    SocketUtils socketUtils;//socket相关
    private boolean isUpdateing = false;//用于判断是否正在升级
    private boolean pauseflag;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_main);
        formate = new SimpleDateFormat("HH:mm:ss");
        //  初始化控件
        mainInitView();
        iconSetListener();
        // 初始化VideoView
        //initVideoInfo();
        //轮播banner
        //initBanner();
//        findViewById(R.id.btn_load).setOnClickListener(this);
//        findViewById(R.id.btn_kill).setOnClickListener(this);
        //  initBanner();
//        findViewById(R.id.btn_load).setOnClickListener(this);
//        findViewById(R.id.btn_kill).setOnClickListener(this);

        //启动socket
        initSocket();
        //启动服务
        startService(new Intent(MainActivity.this, MQService.class));
        //注册广播接收器
        receiver = new MyReceiver();
        IntentFilter filter = new IntentFilter();
        filter.addAction("com.haieros.www.purerunshowsystem.service.MQService");
        MainActivity.this.registerReceiver(receiver, filter);
        //监听时间
        receiverChange = new DataChangeReceiver(socketUtils);
        registerReceiver(receiverChange, new IntentFilter(Intent.ACTION_TIME_TICK));
    }

    //初始化socket并建立链接
    private void initSocket() {
        try {
//            socketUtils = SocketUtils1.getSDKUtilsInstance(MainActivity.this,new SocketBean());
//            socketUtils.setOnDataReceiveListener(this);
            socketUtils = SocketUtils.getSocketUtilsInstance();
            socketUtils.startReadThread();
            socketUtils.setOnDataReceiveListener(this);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
//    private void initVideoInfo() {
//        mlistVideoUri.add("android.resource://" + getPackageName() + "/" + R.raw.img_184);
//        mlistVideoUri.add("android.resource://" + getPackageName() + "/" + R.raw.img_185);
//        mlistVideoUri.add("android.resource://" + getPackageName() + "/" + R.raw.img);
//        // 测试  写入本地视频
//        sdUtils = new SDUtils();
//        try {
//            String uri = sdUtils.writeFile("video", "img_184.mp4", this, R.raw.img_184);
//            mlistStr.add(uri);
//            String uri1 = sdUtils.writeFile("video", "img_185.mp4", this, R.raw.img_185);
//            mlistStr.add(uri1);
//            String uri2 = sdUtils.writeFile("video", "img.mp4", this, R.raw.img);
//            mlistStr.add(uri2);
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//    }

    @Override
    public void onClick(View v) {

    }

    //初始化控件
    private void mainInitView() {
        EventBus.getDefault().register(this);
        mContext = getApplicationContext();
        mWindowManager = (WindowManager) getApplication().getSystemService(getApplication().WINDOW_SERVICE);
        //类型是TYPE_TOAST，像一个普通的Android Toast一样。这样就不需要申请悬浮窗权限了。
        mParams = new WindowManager.LayoutParams(WindowManager.LayoutParams.TYPE_TOAST);
        //初始化后不首先获得窗口焦点。不妨碍设备上其他部件的点击、触摸事件。
        mParams.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;

        mParams.width = WindowManager.LayoutParams.MATCH_PARENT;
        mParams.height = 125;
        mParams.gravity = Gravity.TOP;
        mParams.alpha = 1f;

        mInflater = getLayoutInflater();
        mActivityTopView = mInflater.inflate(R.layout.activity_top, null);
        ivMusic = (ImageView) findViewById(R.id.image_music);
//        ivVideo = (ImageView) findViewById(R.id.image_video);
        ivSetting = (ImageView) findViewById(R.id.image_setting);
        ivGuide = findViewById(R.id.image_guide);
        ivMultimedia = findViewById(R.id.image_multimedia);
//        mMainUpView = (MainUpView) findViewById(R.id.mainUpView1);
        ivHead = mActivityTopView.findViewById(R.id.iv_rundata_head);

//        mMainUpView.setEffectBridge(new EffectNoDrawBridge());
//        bridget = (EffectNoDrawBridge) mMainUpView.getEffectBridge();
//        bridget.setTranDurAnimTime(200);
        // mMainUpView.setUpRectResource(R.drawable.white_light_10); // 设置移动边框的图片.
//        mMainUpView.setDrawUpRectPadding(new Rect(25, 25, 23, 23)); // 边框图片设置间距.
//        mMainUpView.setShadowResource(R.drawable.item_shadow); // 设置移动边框的阴影.
        //初始化速度显示控件
        mSpeed_tv = (TextView) mActivityTopView.findViewById(R.id.tv_speed);
        //初始化坡度控件
        mGradient_tv = (TextView) mActivityTopView.findViewById(R.id.tv_gradient);
        //初始化心跳
        mHeartrate_tv = (TextView) mActivityTopView.findViewById(R.id.tv_heartrate);
        //初始化时间
        mTime_tv = (TextView) mActivityTopView.findViewById(R.id.tv_time);
        //初始化能量消耗
        mKcal_tv = (TextView) mActivityTopView.findViewById(R.id.tv_kcal);
        //初始化路程
        mSpeedunit_tv = (TextView) mActivityTopView.findViewById(R.id.tv_speedunit);
//        ivMusic.requestFocus();
//        mMainUpView.setFocusView(ivMusic, ivVideo, 1.2f);
        ivGuide.requestFocus();
        //mMainUpView.setFocusView(ivGuide, ivMusic, 1.2f);
        //加载头像
        Glide.with(MainActivity.this).asBitmap().load(R.mipmap.bg_main_lb_three_img).into(new BitmapImageViewTarget
                (ivHead) {
            @Override
            protected void setResource(Bitmap resource) {
                RoundedBitmapDrawable circularBitmapDrawable =
                        RoundedBitmapDrawableFactory.create(MainActivity.this.getResources(), resource);
                circularBitmapDrawable.setCircular(true);
                ivHead.setImageDrawable(circularBitmapDrawable);
            }
        });
        mWindowManager.addView(mActivityTopView, mParams);
    }

    public void iconSetListener() {
        ivMusic.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // mMainUpView.setFocusView(ivMusic, null, 1.25f);
//                Intent intent = new Intent(MainActivity.this, MusicActivity.class);
//                startActivity(intent);
                goToThirdAPP("cn.kuwo.music.tv", "cn.kuwo.music.tv.activity.EntryActivity", "music");
                //goToThirdAPP("com.tencent.minihd.qq", "com.tencent.mobileqq.activity.SplashActivity","music");
            }
        });
//        ivMusic.setOnFocusChangeListener(new View.OnFocusChangeListener() {
//            @Override
//            public void onFocusChange(View v, boolean hasFocus) {
//                mMainUpView.setFocusView(ivMusic, ivVideo, 1.25f);
//                mMainUpView.setFocusView(ivMusic, ivSetting, 1.25f);
//                mMainUpView.setFocusView(ivMusic, ivGuide, 1.25f);
//                mMainUpView.setFocusView(ivMusic, ivMultimedia, 1.25f);
//            }
//        });

        ivSetting.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //mMainUpView.setFocusView(ivSetting, ivGuide, 1.25f);
                Intent intent = new Intent(Settings.ACTION_SETTINGS);
                startActivity(intent);
            }
        });
        ivSetting.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                Log.d("TAG", "获得焦点");
//                mMainUpView.setFocusView(ivSetting, ivMusic, 1.25f);
//                mMainUpView.setFocusView(ivSetting, ivVideo, 1.25f);
//                mMainUpView.setFocusView(ivSetting, ivGuide, 1.25f);
//                mMainUpView.setFocusView(ivSetting, ivMultimedia, 1.25f);
            }
        });
        ivGuide.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // mMainUpView.setFocusView(ivGuide, ivMusic, 1.25f);
                startActivity(new Intent(MainActivity.this, StartActivity1.class));
            }
        });
        ivGuide.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                Log.d("TAG", "获得焦点");
//                mMainUpView.setFocusView(ivGuide, ivMusic, 1.25f);
//                mMainUpView.setFocusView(ivGuide, ivVideo, 1.25f);
//                mMainUpView.setFocusView(ivGuide, ivSetting, 1.25f);
//                mMainUpView.setFocusView(ivGuide, ivMultimedia, 1.25f);

            }
        });
        ivMultimedia.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // mMainUpView.setFocusView(ivMultimedia, ivGuide, 1.25f);
                goToThirdAPP("com.gitvdemo.video", "com.gala.video.app.epg.HomeActivity", "video");
            }
        });
        ivMultimedia.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                Log.d("TAG", "获得焦点");
//                mMainUpView.setFocusView(ivMultimedia, ivMusic, 1.25f);
//                mMainUpView.setFocusView(ivMultimedia, ivVideo, 1.25f);
//                mMainUpView.setFocusView(ivMultimedia, ivSetting, 1.25f);
//                mMainUpView.setFocusView(ivMultimedia, ivGuide, 1.25f);
            }
        });
    }

    //跳转第三方应用
    private void goToThirdAPP(String packageName, String className, String thirdAppType) {
        try {
            if (thirdAppType.equals("video")) {
                mThirdAppTypeFlag = true;
            }
            Intent intent = new Intent(Intent.ACTION_MAIN);
            intent.addCategory(Intent.CATEGORY_LAUNCHER);
            ComponentName cn = new ComponentName(packageName, className);
            intent.setComponent(cn);
            startActivity(intent);
        } catch (ActivityNotFoundException e) {
            //第三方应用转到本地音乐视频
            Toast.makeText(getApplicationContext(), "没有此应用", Toast.LENGTH_SHORT).show();
            Log.e("=====", className + "  未找到");
            Intent intent;
            if (thirdAppType.equals("music")) {
                intent = new Intent(MainActivity.this, MusicActivity.class);
                startActivity(intent);
            }
            if (thirdAppType.equals("video")) {
                mThirdAppTypeFlag = false;
                intent = new Intent(getApplicationContext(), GridViewLocalVideoActivity.class);
                startActivity(intent);
            }

        }

    }

    //banner图片轮播
    private void initBanner() {
        /********* VideoView *********/
//        videoUtils = (VideoViewUtil)findViewById(R.id.videoUtils);
//        videoUtils.setDrawingCacheEnabled(true);
//        videoUtils.setVideoURI(Uri.parse(mlistStr.get(0)));
//        videoUtils.setOnCompletionListener(new MyPlayerOnCompletionListener());
//        videoUtils.start();
        /******** Banner *********/
        //banner = (Banner) findViewById(R.id.banner);
        //本地图片数据（资源文件）
//        List<Integer> list = new ArrayList<>();
//        list.add(R.mipmap.bg_main_lb_two_img);
//        list.add(R.mipmap.bg_main_lb_one_img);
//        list.add(R.mipmap.bg_main_lb_four_img);
        // 设置banner
//        banner.setImages(list)
//                .setImageLoader(new GlideImageLoader())
//                .setDelayTime(8000)
//                .setBannerAnimation(CubeOutTransformer.class)
//                .start();

    }

    //socket数据回调
    @Override
    public void onDataReceive(byte[] bytes, int len) {

    }

    //软件更新socket数据回调
    @Override
    public void onUpdateURL(UpdateBean updateBean) {
        if (updateBean != null) {
            Log.i("====haier===", "====haier解析出来的JSON数据====" + updateBean.toString());
            if ((!StringUtils.isEmpty(updateBean.getDisplay_app_path())) && (!StringUtils.isEmpty(updateBean
                    .getDisplay_app_version()))) {
                try {
                    if ((new BigDecimal(Double.parseDouble(getVersionName()))).compareTo(new BigDecimal(Double
                            .parseDouble(updateBean.getDisplay_app_version()))) < 0) {
                        Log.i("TAG", "当前版本低于最新版本，需要升级！==============");
                        if (!isUpdateing) {//如果不在
                            downApkFromServer(updateBean.getDisplay_app_path());
                        }
                    } else {
                        Log.i("TAG", "当前为最新版本！==============");
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } else {
                Log.i("TAG", "数据为空暂不升级！==============");
            }
        }

    }

    //从服务器下载apk
    private void downApkFromServer(String displayPath){
        OkHttpUtils//
                .get()//
                .url(displayPath)//
                .build()//
                .execute(new FileCallBack(filePath, "haier.apk")//
                {
                    @Override
                    public void onBefore(Request request, int id) {
                        super.onBefore(request, id);
                        Log.i("TAG", "调用升级程序！=======start=======");
                    }

                    @Override
                    public void onAfter(int id) {
                        super.onAfter(id);
                        isUpdateing = false;
                    }

                    @Override
                    public void inProgress(float progress, long total, int id) {
                        super.inProgress(progress, total, id);
                        isUpdateing = true;
                        Log.i("apk下载进度===","apk下载进度====="+progress+"======"+total+"======"+id);
                    }

                    @Override
                    public void onError(Call call, Exception e, int id) {
                        isUpdateing = false;
                        Log.i("TAG", "调用升级程序！=======Error======="+e.getLocalizedMessage());
                    }

                    @Override
                    public void onResponse(File response, int id) {
                        Log.i("TAG", "调用升级程序！=======完成=======");
                        isUpdateing = false;
                        SilentInstallUtils.installApk(new File(filePath + File.separator + "haier.apk"),
                                MainActivity.this);
                    }
                });
    }

    /**
     * VodeoView 结束监听
     */
    class MyPlayerOnCompletionListener implements MediaPlayer.OnCompletionListener {

        @Override
        public void onCompletion(MediaPlayer mp) {
            mp.reset();
            itemPosition += 1;
            videoUtils.setVideoURI(Uri.parse(mlistStr.get(itemPosition % mlistStr.size())));
            videoUtils.start();
        }
    }

    @Override
    public void timeToDo(boolean flag) {
        super.timeToDo(flag);

    }

    //设置首页头部数据得显示
    private void setShowData(String speedNum, String gradientNum, String heartrateNum, String speedNumberNum,
                             String timeNum, String kcalNum, String speedUnitNum) {
        //设置速度
        mSpeed_tv.setText(speedNum);
        //设置坡度
        mGradient_tv.setText(gradientNum);
        //设置心跳
        mHeartrate_tv.setText(heartrateNum);
        //设置时间
        mTime_tv.setText(timeNum);
        //设置能量消耗
        mKcal_tv.setText(kcalNum);
        //设置路程
        mSpeedunit_tv.setText(speedUnitNum);
    }

    @Override
    protected void onResume() {
        super.onResume();
//                if(DateJudgeUtil.getInstence(this).judgeTimeTwo(new Date()))
//        {
//            mActivityTopView.setVisibility(View.INVISIBLE);
//            Toast.makeText(this,"pauseflag跳转",Toast.LENGTH_SHORT).show();
//            Intent  intent2 = new Intent(this,LaunchEquipmenActivity.class);
//            startActivity(intent2);
//            //finish();
//        }
//        pauseflag=(boolean) SharedPreferencesUtils.getParam(this,"pauseflag",false);
//        if(pauseflag)
//        {
//            if(mActivityTopView!=null)
//            {
//                mActivityTopView.setVisibility(View.INVISIBLE);
//            }
//
//            Toast.makeText(this,"pauseflag跳转",Toast.LENGTH_SHORT).show();
//            Intent  intent2 = new Intent(this,LaunchEquipmenActivity.class);
//            startActivity(intent2);
//        }
        Intent intent = new Intent("com.tpv.xmic.SOURCECHANGE");
        intent.putExtra("source", "E_INPUT_SOURCE_STORAGE");
        intent.putExtra("isgotolauncher", "true");
        intent.putExtra("name", "system");
        mContext.sendBroadcast(intent);
        Utils.setBackground(false);
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (mThirdAppTypeFlag) {
            mActivityTopView.setVisibility(View.INVISIBLE);
        }
        Utils.setBackground(true);
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        if (mActivityTopView.getVisibility() == View.INVISIBLE) {
            mActivityTopView.setVisibility(View.VISIBLE);
            mThirdAppTypeFlag = false;
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
    }

    /**
     * 加载热补丁插件
     */
    public void loadPatch() {
        TinkerInstaller.onReceiveUpgradePatch(getApplicationContext(),
                Environment.getExternalStorageDirectory().getAbsolutePath() + "/myTinkerDemo/TinkerPatch.apk");
        File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/myTinkerDemo/TinkerPatch" +
                ".apk");

        try {
            getFileSize(file);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static long getFileSize(File file) throws Exception {
        long size = 0;
        if (file.exists()) {
            FileInputStream fis = null;
            fis = new FileInputStream(file);
            size = fis.available();
            Log.e("--------", "============" + size);
        } else {
            file.createNewFile();
            Log.e("获取文件大小", "文件不存在!");
        }
        return size;
    }

    /**
     * 杀死应用加载补丁
     */
    public void killApp() {
        ShareTinkerInternals.killAllOtherProcess(getApplicationContext());
        android.os.Process.killProcess(android.os.Process.myPid());
    }

    /**
     * 获取当前程序的版本号
     */
    private String getVersionName() throws Exception {
        //获取packagemanager的实例
        PackageManager packageManager = getPackageManager();
        //getPackageName()是你当前类的包名，0代表是获取版本信息
        PackageInfo Info = null;
        Info = packageManager.getPackageInfo(getPackageName(), 0);
        return Info.versionName;
    }

    @Subscribe
    public void onEvent(String event) {
    /* Do something */
        Log.e("iiiiii", "收到");
        if (event.equals("onCreate")) {
            if (mActivityTopView.getVisibility() == View.VISIBLE) {
                mActivityTopView.setVisibility(View.INVISIBLE);
            }
        }
        if (event.equals("onDestroy")) {
            if (!mThirdAppTypeFlag) {
                if (mActivityTopView.getVisibility() == View.INVISIBLE) {
                    mActivityTopView.setVisibility(View.VISIBLE);
                }
            }

        }

    }

    /**
     * 遥控器点击监听
     *
     * @param keyCode
     * @param event
     * @return
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        Log.e("TAG", "onKeyDown:-- " + keyCode);

        if (keyCode == KeyEvent.KEYCODE_BACK) {
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void onBackPressed() {
        return;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        try {
            EventBus.getDefault().register(this);
            //结束服务
            unregisterReceiver(receiver);
            unregisterReceiver(receiverChange);
            stopService(new Intent(MainActivity.this, MQService.class));
            stopService(new Intent(MainActivity.this, MusicService.class));
            if (mWindowManager != null && mActivityTopView != null) {
                mWindowManager.removeView(mActivityTopView);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {

        }
    }

    Gson gson = new Gson();

    public class MyReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {

            Bundle bundle = intent.getExtras();
            mqMessage = bundle.getString("message");
            Log.i("接受的推送数据", "==============" + mqMessage);
            try {
                // s = mqMessage.split(",");
                timeNow = formate.format(new java.util.Date());
                //设置数据
                Log.e("TAG", "onReceive: " + s);
//                setShowData(s[0], s[1], s[2], s[3], timeNow, s[4], s[5]);
                RunDataModel result = gson.fromJson(mqMessage, RunDataModel.class);
                setShowData(result.getMsg().getSpeed(), result.getMsg().getGradient(), result.getMsg().getHeart_beat(),
                        result.getMsg().getDistance(), timeNow, result.getMsg().getCalorie(), result.getMsg()
                                .getRun_duration());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }


    //显示升级对话框
    public void ShowDialog() {
        deleteDialog = new DeleteDialog(MainActivity.this);
        deleteDialog.setMessage("是否要更新版本");
        deleteDialog.show();
        deleteDialog.setCanceledOnTouchOutside(false);
        deleteDialog.setYesOnclickListener("确定", new PhoneDialog.onYesOnclickListener() {
            @Override
            public void onYesClick() {
                //从服务器上下载apk
                downLoadApk();
            }
        });
        deleteDialog.setNoOnclickListener("忽略", new PhoneDialog.onNoOnclickListener() {
            @Override
            public void onNoClick() {
                deleteDialog.dismiss();

            }
        });
    }

    /**
     * 将下载的信息接收，确定是否下载完成。
     */

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case UPDATA_CLIENT:
                    // 对话框通知用户升级程序
                    ShowDialog();
                    break;
                case GET_UNDATAINFO_ERROR:
                    // 服务器超时
                    Toast.makeText(getApplicationContext(), "获取服务器更新信息失败", Toast.LENGTH_SHORT).show();
                    break;
                case DOWN_ERROR:
                    // 下载apk失败
                    Toast.makeText(getApplicationContext(), "下载新版本失败", Toast.LENGTH_SHORT).show();
                    break;
            }
        }
    };

    /**
     * 从服务器中下载apk
     */
    protected void downLoadApk() {
        if (deleteDialog != null) {
            deleteDialog.dismiss();
        }
        final ProgressDialog pd;    //进度条对话框
        pd = new ProgressDialog(this);
        pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        pd.setMessage("正在下载更新");
        pd.show();
        pd.setCanceledOnTouchOutside(false);
        new Thread() {
            @Override
            public void run() {
                try {
                    InputStream inputStream;
                    inputStream = MainActivity.this.getResources().getAssets().open("TinkerPatch.apk");
                    File file = getFileFromServer1(inputStream, pd);
                    sleep(3000);
                    //安装apk
                    Log.e("-------", "=====开始安装");
                    installApk(file);
                    pd.dismiss(); //结束掉进度条对话框
                } catch (Exception e) {
                    Message msg = new Message();
                    msg.what = DOWN_ERROR;
                    handler.sendMessage(msg);
                    if (pd.isShowing())
                        pd.dismiss();
                    e.printStackTrace();
                }
            }
        }.start();
    }

    /**
     * 安装apk
     */

//    protected void installApk(File file) {
//        //***************************************************************************************
//        Intent intent = new Intent(Intent.ACTION_VIEW);
//        //判断是否是AndroidN以及更高的版本
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
//            Uri contentUri = FileProvider.getUriForFile(MainActivity.this, "com.haieros.www.purerunshowsystem
// .provider", file);
//            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
//            intent.setDataAndType(contentUri, "application/vnd.android.package-archive");
//        } else {
//
//            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//            intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
//        }
//        MainActivity.this.startActivity(intent);
//    }
    protected void installApk(File file) {
        try {
            PackageManager packageManager = getPackageManager();
            @SuppressLint("PrivateApi") Method method = packageManager.getClass().getDeclaredMethod("installPackage",
                    new Class[]{Uri.class, IPackageInstallObserver.class, int.class, String.class});
            method.setAccessible(true);
            Uri apkUri = Uri.fromFile(file);
            Log.e("-------", "=====正在安装");
            method.invoke(packageManager, new Object[]{apkUri, new IPackageInstallObserver.Stub() {
                @Override
                public void packageInstalled(String pkgName, int resultCode) throws RemoteException {
                    Log.e("========升级信息", "packageInstalled = " + pkgName + "; resultCode = " + resultCode);
                }
            }, Integer.valueOf(2), "com.ali.babasecurity.yunos"});
            //PackageManager.INSTALL_REPLACE_EXISTING = 2;
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取本地apk
     *
     * @param pd
     * @return
     * @throws Exception
     */
    public File getFileFromServer1(InputStream inputStream, ProgressDialog pd) throws Exception {
        //如果相等的话表示当前的sdcard挂载在手机上并且是可用的
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            try {
                //获取到文件的大小
                pd.setMax(inputStream.available());

                File file = new File(filePath);
                if (!file.exists()) {
                    file.mkdirs();
                }

                FileOutputStream fileOutputStream = new FileOutputStream(filePath + "/TinkerPatch.apk");
                byte[] buffer = new byte[512];
                int count = 0;
                int len;
                while ((len = inputStream.read(buffer)) > 0) {
                    fileOutputStream.write(buffer, 0, len);
//                    Log.e("-------", "=====1");
                    count += len;
                    //获取当前下载量
                    pd.setProgress(count);
                    //下载转换为M显示
                    float all = Float.parseFloat(inputStream.available() / 1024.0 / 1024.0 + "");
                    float percent = Float.parseFloat(count / 1024.0 / 1024.0 + "");
                    pd.setProgressNumberFormat(String.format("%.2fM/%.2fM", percent, all));
                }
                fileOutputStream.flush();
                fileOutputStream.close();
                inputStream.close();
                System.out.println("success");
            } catch (IOException e) {
                e.printStackTrace();
            }
            File file = new File(filePath + "/TinkerPatch.apk");
            return file;
        } else {
            return null;
        }
    }

    /**
     * 从服务器下载apk:更新
     */

    public File getFileFromServer(String path, ProgressDialog pd) throws Exception {
        //如果相等的话表示当前的sdcard挂载在手机上并且是可用的
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            URL url = new URL(path);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.connect();
            conn.setConnectTimeout(5000);
            //获取到文件的大小
            pd.setMax(conn.getContentLength());
            InputStream is = conn.getInputStream();//通过输入流获取数据
            File file = new File(Environment.getExternalStorageDirectory(), "TinkerPatch.apk");
            FileOutputStream fos = new FileOutputStream(file);
            BufferedInputStream bis = new BufferedInputStream(is);
            byte[] buffer = new byte[1024];
            int len;
            int total = 0;
            while ((len = bis.read(buffer)) != -1) {

                fos.write(buffer, 0, len);
                total += len;
                //获取当前下载量
                pd.setProgress(total);
                //下载转换为M显示
                float all = Float.parseFloat(conn.getContentLength() / 1024.0 / 1024.0 + "");
                float percent = Float.parseFloat(total / 1024.0 / 1024.0 + "");
                pd.setProgressNumberFormat(String.format("%.2fM/%.2fM", percent, all));
            }
            fos.close();
            bis.close();
            is.close();
            return file;
        } else {
            return null;
        }
    }


    private void write() {
        InputStream inputStream;
        try {
            inputStream = MainActivity.this.getResources().getAssets().open("TinkerPatch.apk");
            Log.e("-------", "=====" + inputStream.available());
            File file = new File(filePath);
            if (!file.exists()) {
                file.mkdirs();
            }
//            Log.e("-------", "=====1");
            FileOutputStream fileOutputStream = new FileOutputStream(filePath + "/TinkerPatch.apk");
            byte[] buffer = new byte[512];
            int count = 0;
            while ((count = inputStream.read(buffer)) > 0) {
                fileOutputStream.write(buffer, 0, count);
            }
            fileOutputStream.flush();
            fileOutputStream.close();
            inputStream.close();
            System.out.println("success");
            Toast.makeText(MainActivity.this, "添加成功", Toast.LENGTH_SHORT).show();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private String[] names = {"abcd.mp3", "左凡.mp3"};

    private void writeMusic() {
        try {
            for (int i = 0; i < names.length; i++) {
                InputStream inputStream = MainActivity.this.getResources().getAssets().open(names[i]);
                Log.e("-------", "=====" + inputStream.available());
//                File file = new File(musicFilePath);
                File file = new File(filePath);
                if (!file.exists()) {
                    file.mkdirs();
                }
//            Log.e("-------", "=====1");
                FileOutputStream fileOutputStream = new FileOutputStream(filePath + "/" + names[i]);
//                FileOutputStream fileOutputStream = new FileOutputStream(musicFilePath + "/" + names[i]);
                byte[] buffer = new byte[512];
                int count = 0;
                while ((count = inputStream.read(buffer)) > 0) {
                    fileOutputStream.write(buffer, 0, count);
                }
                fileOutputStream.flush();
                fileOutputStream.close();
                inputStream.close();
            }
            System.out.println("success");
            Toast.makeText(MainActivity.this, "添加成功", Toast.LENGTH_SHORT).show();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private boolean isExist() {
        File file = new File(filePath + "/TinkerPatch.apk");
        if (file.exists()) {
            return true;
        } else {
            return false;
        }
    }
}
